package mysql

import (
	"ShortLink/Core/LogHelper"

	"github.com/spf13/viper"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var WriteDB *gorm.DB
var ReadDB *gorm.DB

func Init() {
	if WriteDB != nil && ReadDB != nil {
		return
	}
	/*
		newLogger := logger.New(
		 	log.New(os.Stdout, "\r\n", log.LstdFlags),
		 	logger.Config{
		 		SlowThreshold: time.Second,
		 		LogLevel:      logger.Info,
		 		Colorful:      true,
		 	})
		 WriteDB, _ = gorm.Open(mysql.Open(viper.GetString("mysql.conns.master")), &gorm.Config{Logger: newLogger})
		 ReadDB, _ = gorm.Open(mysql.Open(viper.GetString("mysql.conns.slave")), &gorm.Config{Logger: newLogger})
	*/
	WriteDB, _ = gorm.Open(mysql.Open(viper.GetString("mysql.conns.master")))
	ReadDB, _ = gorm.Open(mysql.Open(viper.GetString("mysql.conns.slave")))
	setDB(WriteDB)
	setDB(ReadDB)
}

func setDB(db *gorm.DB) {
	db.Callback().Create().After("gorm:create").Register("gormzap", func(db *gorm.DB) {
		LogHelper.Logger.Info("Record created", zap.String("table", db.Statement.Table), zap.String("sql", db.Statement.SQL.String()))
	})

	db.Callback().Update().After("gorm:update").Register("gormzap", func(db *gorm.DB) {
		LogHelper.Logger.Info("Record updated", zap.String("table", db.Statement.Table), zap.String("sql", db.Statement.SQL.String()))
	})

	db.Callback().Delete().After("gorm:delete").Register("gormzap", func(db *gorm.DB) {
		LogHelper.Logger.Info("Record deleted", zap.String("table", db.Statement.Table), zap.String("sql", db.Statement.SQL.String()))
	})

	db.Callback().Query().After("gorm:query").Register("gormzap", func(db *gorm.DB) {
		LogHelper.Logger.Info("Record query", zap.String("table", db.Statement.Table), zap.String("sql", db.Statement.SQL.String()))
	})
}
